use std::env;

use crate::types::{Status, Account};
use crate::components::{post::PostComponent, user_card::UserCardComponent};
use crate::utils::auth;
use yew::{function_component, html, use_effect_with, use_state, Html, UseStateHandle};
use gloo_net::http::Request;

#[function_component(Root)]
pub fn root() -> Html {
    let statuses: UseStateHandle<Vec<Status>> = use_state(|| vec![]);
    {
        let statuses = statuses.clone();
        use_effect_with((), move |_| {
            wasm_bindgen_futures::spawn_local(async move {
                let fetched_status: Vec<Status> = Request::get(&format!("https://{}/api/v1/accounts/{}/statuses", env!("SERVER_URL"), env!("USER_ID")))
                    .send()
                    .await
                    .unwrap()
                    .json()
                    .await
                    .unwrap();
                statuses.set(fetched_status);
            });
        });
    }

    let account: UseStateHandle<Account> = use_state(|| Account {..Default::default()});
    {
        let account = account.clone();
        use_effect_with((), move |_| {
            wasm_bindgen_futures::spawn_local(async move {
                let fetched_account: Account = Request::get(&format!("https://{}/api/v1/accounts/{}", env!("SERVER_URL"), env!("USER_ID")))
                    .send()
                    .await
                    .unwrap()
                    .json()
                    .await
                    .unwrap();
                account.set(fetched_account);
            });
        });
    }

    let status_render = statuses.iter().map(|status| html! {
        <PostComponent status={status.to_owned()} />
    });
    
    use_effect_with((), move |_| {
        wasm_bindgen_futures::spawn_local(async move {
            auth::oauth().await;
        });
    });

    html! {
        <main>
            <div class="page">
                <div class="f">
                    <UserCardComponent account={account.to_owned()} /> 
                    {for status_render}
                    </div>
            </div>
        </main>
    }
}

